import {commonRoutes} from './routers'
import {getToken, removeToken} from '@/libs/auth'
import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const createRouter = () => new VueRouter({
    // mode: 'history', // require service support
    scrollBehavior: () => ({y: 0}),
    routes: commonRoutes
});

const Router = createRouter();

Router.beforeEach((to, from, next) => {
    if (to.name === 'logout') {
        removeToken();
        return next();
    }
    if (!getToken() && to.name !== 'login') {
        return next({name: 'login'})
    }
    if (getToken() && to.name === 'login') {
        return next({name: from.name})
    }
    next();
});

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
    const newRouter = createRouter();
    Router.matcher = newRouter.matcher // reset router
}

export default Router